package com.itheima.controller;

import com.itheima.pojo.Result;
import jakarta.servlet.http.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@Slf4j
public class SessionController {

    /**
     * Cookie会话技术
     * 1.模拟登录，设置Cookie
     */
    @GetMapping("/c1")
    public Result cookie1(HttpServletResponse  response){
        //模拟获取账号。。。登陆成功
            response.addCookie(new Cookie("username","itheimazhang"));
            return Result.success();
        //设置 Cookie会话信息
    }

    @GetMapping("/c2")
    public Result cookie2 (HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie:cookies){
            if(cookie.getName().equals("login_username")){
                System.out.println("login_username: "+cookie.getValue());
                ////输出name为login_username的cookie
            }
        }
        return Result.success();
    }



    @GetMapping("/session1")
    public Result sesion1(HttpSession session){
        log.info("HttpSeesion-s1:{}",session.hashCode());

        session.setAttribute("loginUser","tom");//往session中存储数据

        return Result.success();

    }

    @GetMapping("/session2")
public Result session2(HttpServletRequest request){
        HttpSession session = request.getSession();

        log.info("HttpSession-s2:{}",session.hashCode());
        Object loginUser = session.getAttribute("loginUser");
        log.info("loginUser:{}",loginUser);
        return Result.success(loginUser) ;
    }

}
